const sequelize = require('../config/db');
const User = require('./User');
const Category = require('./Category');
const Account = require('./Account');

// 定义关联关系
User.hasMany(Account, { foreignKey: 'userId' });
Category.hasMany(Account, { foreignKey: 'categoryId' });
Account.belongsTo(User, { foreignKey: 'userId' });
Account.belongsTo(Category, { foreignKey: 'categoryId' });

// 同步数据库
const syncDatabase = async () => {
  try {
    await sequelize.sync({ alter: true });
    console.log('数据库同步成功');
    
    // 初始化默认分类
    const defaultCategories = [
      { id: 1, name: '网站', description: '各类网站账号' },
      { id: 2, name: '应用', description: '移动应用账号' },
      { id: 3, name: '社交媒体', description: '社交平台账号' },
      { id: 4, name: '金融', description: '银行、支付等金融账号' },
      { id: 5, name: '其他', description: '其他类型账号' }
    ];
    
    for (const category of defaultCategories) {
      await Category.findOrCreate({
        where: { id: category.id },
        defaults: category
      });
    }
    
    console.log('默认分类初始化完成');
  } catch (error) {
    console.error('数据库同步失败:', error);
  }
};

module.exports = {
  sequelize,
  User,
  Category,
  Account,
  syncDatabase
};